let prefix = "/jzweb/trackDraw";
let isDrawing = null;
let flag = false; // 标记是否正在进行抽签
let animationId;
let paging = 1;

$(function() {
    document.title = '竞赛管理平台'; // 动态设置网页标题
    $('link[rel="shortcut icon"]').attr('href', `${'../../static/favicon.ico'}`)
    if(window.location.href.split('?')[1]) {
        $('.openPages').show()
    }else {
        $('.openPages').hide()
    }

    $.ajax({
        cache : true,
        type : "post",
        url : "/jzweb/stuSignUpCom/cbatchList",
        data:{
            types: 3,
        },
        error : function(request) {
            parent.layer.alert("Connection error");
        },
        success : function(data) {

            if (data.code == 0) {
                let str = '';
                data.data?.map(function (v,k){
                    // if ( k == 0 ) str += `<option value="">请选择</option>`
                    str += `<option value="${v.id}">${v.name}</option>`
                })
                $("#cbatchName").html(str);
                load();
            } else {
                parent.layer.alert(data.msg)
            }
        }
    });

    $("#cbatchName").change(() => {
        reLoad()
    })

});

function columnsCreate() {
    return [
        { field: `unitName`, title: '学校名称' },
        { field: `name1`, title: '参赛选手一' },
        { field: `sort1`, title: '参赛选手顺序号', class: 'sort1-cell' },
        { field: `name2`, title: '参赛选手二' },
        { field: `sort2`, title: '参赛选手顺序号', class: 'sort2-cell' },
    ];
}

function load() {
    $('#exampleTable').bootstrapTable({
        method: 'get',
        url: '/jzweb/trackDraw/trackListXinJiang',
        iconSize: 'outline',
        toolbar: '#exampleToolbar',
        theadClasses: "thead-dark",
        striped: true,
        dataType: "json",
        pagination: true,
        singleSelect: false,
        pageSize: 999999,
        pageNumber: 1,
        showColumns: false,
        sidePagination: "server",
        queryParamsType: "",
        paginationDetail: false,
        pageList: [15, 25, 50, 100],
        queryParams: function(params) {
            paging = params.pageNumber;
            return {
                current: params.pageNumber,
                size: params.pageSize,
                cbatchId: $('#cbatchName').val()
            };
        },
        responseHandler: function(res) {
            if (res.code !== '0') {
                layer.msg(res.msg);
                return false;
            }
            let { data } = res;
            isDrawing = data[0];
            return {
                "rows": data,
                "total": res.data.total,
            };
        },
        columns: columnsCreate()
    });
}

function reLoad() {
    $('#exampleTable').bootstrapTable('refresh');
}

/**
 * 导出
 */
function downExcelModelFile() {
    layer.confirm('您确定要导出吗？', {
        btn1: function(index) {
            if (!isDrawing) {
                layer.msg('请先完成抽签');
                layer.close(index);
                return;
            }
            try {
                window.location.href = `/jzweb/trackDraw/downloadImportTemplateXinJiang?cbatchId=${$('#cbatchName').val()}`;
                layer.close(index);
            } catch (e) {
                layer.msg('导出失败');
            }
        }
    });
}

/**
 * 下载导入模板
 */
const downloadExcelModelFile = () => {
    window.location.href = "/jzweb/trackDraw/exportTrackDraw ";
}

function trackDrawCreate() {
    $.ajax({
        type: "get",
        url: `/jzweb/trackDraw/listXinJiang?current=${paging}&size=15&cbatchId=${$('#cbatchName').val()}`,
        async: false,
        error: function(request) {
            parent.layer.alert(request);
        },
        success: function(res) {
            if (res.code === '0') {
                $('#exampleTable').bootstrapTable('load', res.data);
                let options = $('#exampleTable').bootstrapTable('getOptions');
                options.totalRows = res.data.length;
                $('#exampleTable').bootstrapTable('refreshOptions', options);
                layer.msg('抽签完毕');
            } else {
                parent.layer.alert(res.msg);
            }
        }
    });
}


/**
 * 大屏抽签
 */
const openPage =() => {
    window.open('/jzweb/trackDraw/trackDraw2',"_blank")
}

/**
 * 开始抽签
 */
const drawBButton = () => {
    let index = layer.confirm('确定开始抽签？', {
        btn: ['确定', '取消']
    }, function() {
        let rows = $('#exampleTable').bootstrapTable('getData');
        if(!rows.length) {
            return layer.msg('请导入信息');
        }
        if (flag) {
            return layer.msg('抽签中');
        }
        flag = true;
        animateNumbers();
        layer.close(index);
    });
}

/**
 * 停止抽签
 */
const stopButton = () => {
    let index = layer.confirm('确定停止抽签？', {
        btn: ['确定', '取消']
    }, function() {
        if (flag) {
            flag = false; // 立即停止标志
            cancelAnimationFrame(animationId);
            trackDrawCreate(); // 获取抽签结果
        } else {
            if (isDrawing) {
                layer.msg('抽签已完成');
                return;
            }
            layer.msg('请先完成抽签');
        }
        layer.close(index);
    });
}

// 定义签池
const poolA = Array.from({length: 17}, (_, i) => `A${(i+1).toString().padStart(2, '0')}`);
const poolB = Array.from({length: 16}, (_, i) => `B${(i+1).toString().padStart(2, '0')}`);
const poolC = Array.from({length: 16}, (_, i) => `C${(i+1).toString().padStart(2, '0')}`);

function animateNumbers() {
    if (!flag) {
        cancelAnimationFrame(animationId);
        return;
    }

    let rows = $('#exampleTable').bootstrapTable('getData');
    if (rows.length === 0) return layer.msg('暂无选手信息');

    // 获取总选手数（学校数 * 2）
    const totalCount = rows.length * 2;

    // 更新DOM
    $('#exampleTable tbody tr').each(function(index) {
        // 为每位选手生成独立的随机顺序号
        const randomSort1 = getRandomNumber(1, totalCount);
        const randomSort2 = getRandomNumber(1, totalCount);

        // 更新表格中的顺序号显示
        $(this).find('.sort1-cell').text(randomSort1);
        $(this).find('.sort2-cell').text(randomSort2);
    });

    animationId = requestAnimationFrame(animateNumbers);
}

// 辅助函数：生成指定范围内的随机数
function getRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}